package cn.jksoft.businessclient.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Observable;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding.widget.RxTextView;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingApi;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseActivity;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseConfig;
import cn.jksoft.businessclient.bean.LoginEntity;
import cn.jksoft.businessclient.utils.DialogHelp;
import rx.Observer;
import rx.Subscriber;
import rx.android.plugins.RxAndroidPlugins;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import rx.android.*;

/**
 * Created by RogersHuang on 16/4/6.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.et_account)
    EditText etAccount;
    @Bind(R.id.et_password)
    EditText etPassword;
    @Bind(R.id.btn_login)
    AppCompatButton btnLogin;
    @Bind(R.id.tv_login_problem)
    TextView tvLoginProblem;

    private ProgressDialog progressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        etAccount.setText(BaseApplication.getInstance().getPreference().getString(BaseConfig.USER_NAME, ""));
        etPassword.setText(BaseApplication.getInstance().getPreference().getString(BaseConfig.PASSWORD,""));
        hideStatusBar();
        rx.Observable<CharSequence> accountObservable = RxTextView.textChanges(etAccount);
        rx.Observable<CharSequence> pwdObservable = RxTextView.textChanges(etPassword);
        rx.Observable.combineLatest(accountObservable,
                pwdObservable,
                new Func2<CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence newAccount,
                                        CharSequence newPassword) {
                        boolean accountValid = newAccount.length()>0;
                        boolean pwdValid = newPassword.length()>0;
                        return accountValid && pwdValid;

                    }
                }).subscribe(new Observer<Boolean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(Boolean isValid) {
                        btnLogin.setEnabled(isValid);
                        btnLogin.setTextColor(isValid?getResources().getColor(R.color.white):getResources().getColor(R.color.main_gray));
                    }
                });
    }

    @Override
    @OnClick(R.id.btn_login)
    public void onClick(View v) {
        if(checkInput()){
            loginRequest();
        }
    }
    private boolean checkInput() {
        if (etAccount.getText().length() == 0) {
            showToast("请输入账号");
            return false;
        } else if (etPassword.getText().length() == 0) {
            showToast("请输入密码");
            return false;
        } else {
            return true;
        }
    }

    private void loginRequest(){
        if (checkInput()) {
            progressDialog = DialogHelp.getWaitDialog(LoginActivity.this,"正在登录...");
            progressDialog.show();
            JSONObject json = null;
            try {
                json = new JSONObject();
                json.put("login", etAccount.getText().toString());
                json.put("password", etPassword.getText().toString());
                String cid = BaseApplication.getInstance().getPreference().getString(BaseConfig.PUSH_CID);
                json.put("cid",cid!=null?cid:"");
                json.put("channelType","android");
            } catch (Exception e) {
                e.printStackTrace();
            }
            ReceivingApi service = ReceivingService.createReceivingService();
            service.login(json.toString())
                    .observeOn(Schedulers.io())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<LoginEntity>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onNext(LoginEntity entity) {
                            String retCode = entity.getIs_successful();
                            if ("1".equals(retCode)) {
                                BaseApplication.getInstance().getPreference().putString(BaseConfig.USER_NAME,etAccount.getText().toString()).commit();
                                BaseApplication.getInstance().getPreference().putString(BaseConfig.PASSWORD,etPassword.getText().toString()).commit();
                                BaseApplication.getInstance().setLoginEntity(entity);
                                if ("COMPANY".equals(entity.getPuxsoftLoginDTO().getAdminUserType())) {
                                    readyGo(WebViewActivity.class);
                                }else {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    startActivity(intent);
                                }
                                finish();
                            } else {
                                showToast(entity.getResult());
                            }
                            progressDialog.dismiss();
                        }
                    });
        }
    }
}
